/*
 * Copyright 2016-2017 lei.xu<xulei2008xulei@163.com>.
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.san21go.jfinfunc.math.covariance;

import org.san21go.jfinfunc.AbstractFunction;
import org.san21go.jfinfunc.FinFuncRuntimeException;
import org.san21go.jfinfunc.jfinfunc.math.AVERAGE;

/**
 * 返回总体协方差，即两个数据集中每对数据点的偏差乘积的平均数。<br/>
 * 利用协方差确定两个数据集之间的关系。<br/>
 * COVARIANCE.P 函数
 * 
 * @author xulei
 *
 */
public class COVARIANCEP extends AbstractFunction<Double> {
	private double[] value1s;
	private double[] value2s;

	public COVARIANCEP(double[] value1s, double[] value2s) {
		this.value1s = value1s;
		this.value2s = value2s;
	}

	@Override
	public Double evaluate() {
		if (value1s == null || value2s == null || value1s.length == 0 || value1s.length != value2s.length) {
			throw new FinFuncRuntimeException("参数错误");
		}
		if (value1s.length == 1) {
			return 0D;
		}

		double avg1 = new AVERAGE(value1s).evaluate();
		double avg2 = new AVERAGE(value2s).evaluate();

		double den = 0;
		for (int i = 0; i < value1s.length; i++) {
			double value1 = value1s[i];
			double value2 = value2s[i];
			den = den + (value1 - avg1) * (value2 - avg2);
		}

		// 此处标准偏差的计算使用“n”方法
		return den / (value1s.length);
	}

}
